import asyncio
import websockets
import json
import base64
import time
import logging
from modules.auth_utils import generate_auth_url

async def speech_to_text(audio_file_path, config):
    ws_url = generate_auth_url('wss://iat-api.xfyun.cn/v2/iat', config.XUNFEI_API_KEY, config.XUNFEI_SECRET_KEY)
    final_text = []

    async def send_audio(websocket):
        frame_size = 8000  # 每帧音频数据的大小
        intervel = 0.04    # 发送间隔，单位：秒
        status = 0         # 音频状态，0-首次发送，1-持续发送，2-发送结束

        with open(audio_file_path, 'rb') as fp:
            while True:
                buf = fp.read(frame_size)
                if not buf:
                    status = 2
                if status == 0:
                    d = {
                        "common": {"app_id": config.XUNFEI_APP_ID},
                        "business": {
                            "language": "zh_cn",
                            "domain": "iat",
                            "accent": "mandarin",
                            "vad_eos": 5000,
                            "dwa": "wpgs"
                        },
                        "data": {
                            "status": 0,
                            "format": "audio/L16;rate=16000",
                            "audio": str(base64.b64encode(buf), 'utf-8'),
                            "encoding": "raw"
                        }
                    }
                    status = 1
                elif status == 1:
                    d = {
                        "data": {
                            "status": 1,
                            "format": "audio/L16;rate=16000",
                            "audio": str(base64.b64encode(buf), 'utf-8'),
                            "encoding": "raw"
                        }
                    }
                elif status == 2:
                    d = {
                        "data": {
                            "status": 2,
                            "format": "audio/L16;rate=16000",
                            "audio": '',
                            "encoding": "raw"
                        }
                    }
                    await websocket.send(json.dumps(d))
                    time.sleep(1)
                    break
                await websocket.send(json.dumps(d))
                await asyncio.sleep(intervel)

    async def receive_result(websocket):
        while True:
            try:
                message = await websocket.recv()
                response = json.loads(message)
                if response['code'] != 0:
                    logging.error(f"错误代码：{response['code']}，错误信息：{response['message']}")
                    break
                else:
                    data = response.get('data', {})
                    result = data.get('result', {})
                    ws_list = result.get('ws', [])
                    for ws in ws_list:
                        for cw in ws['cw']:
                            w = cw.get('w', '')
                            final_text.append(w)
                    if data.get('status') == 2:
                        break
            except websockets.exceptions.ConnectionClosed:
                logging.info("连接已关闭")
                break

    async with websockets.connect(ws_url) as websocket:
        send_task = asyncio.create_task(send_audio(websocket))
        receive_task = asyncio.create_task(receive_result(websocket))
        await asyncio.gather(send_task, receive_task)

    return ''.join(final_text)